/**
 * Copyright(c)2013 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.common.custom;


import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;

import com.pmc.dwa.common.exception.PmcRuntimeException;

/**
 * @description 通过@ResponseBody方式返回java.sql.Date/java.sql.Timestamp类型时的json格式为自定义格式
 * @author aokunsang
 * @date 2013-5-28
 */
public class CustomObjectMapper extends ObjectMapper {

	private String timestampFormatPattern;
	private String dateFormatPattern;
	
	public CustomObjectMapper(){
		CustomSerializerFactory factory = new CustomSerializerFactory();
		factory.addGenericMapping(Timestamp.class, new JsonSerializer<Timestamp>(){
			@Override
			public void serialize(Timestamp value, 
					JsonGenerator jsonGenerator,
					SerializerProvider provider) throws IOException,
					JsonProcessingException {
				if(timestampFormatPattern==null){
					throw new PmcRuntimeException("timestampFormatPattern[日期格式化样式]属性值不能为空");
				}
				SimpleDateFormat sdf = new SimpleDateFormat(timestampFormatPattern);
				try {
					jsonGenerator.writeString(sdf.format(value));
				} catch (Exception e) {
					throw new PmcRuntimeException("转换日期格式"+timestampFormatPattern+"失败。",e);
				}
			}
		});
		factory.addGenericMapping(Date.class, new JsonSerializer<Date>(){
			@Override
			public void serialize(Date value, 
					JsonGenerator jsonGenerator, 
					SerializerProvider provider)
					throws IOException, JsonProcessingException {
				if(dateFormatPattern==null){
					throw new PmcRuntimeException("dateFormatPattern[日期格式化样式]属性值不能为空");
				}
				SimpleDateFormat sdf = new SimpleDateFormat(dateFormatPattern);
				try {
					jsonGenerator.writeString(sdf.format(value));
				} catch (Exception e) {
					throw new PmcRuntimeException("转换日期格式"+dateFormatPattern+"失败。",e);
				}
			}
		});
		this.setSerializerFactory(factory);
	}

	/**
	 * @param dateFormatPattern the dateFormatPattern to set
	 */
	public void setDateFormatPattern(String dateFormatPattern) {
		this.dateFormatPattern = dateFormatPattern;
	}

	/**
	 * @param timestampFormatPattern the timestampFormatPattern to set
	 */
	public void setTimestampFormatPattern(String timestampFormatPattern) {
		this.timestampFormatPattern = timestampFormatPattern;
	}
}
